//
//  CoreDataFile.swift
//  SwiftPanda
//
//  Created by 余意 on 2017/2/28.
//  Copyright © 2017年 余意. All rights reserved.
//

import Foundation
import UIKit

import CoreData

enum UserInfoType {
    case isFirst
    case token
    case mobile
    case nickName
    case headImageUrl
    case setting
    case unKnow
}


/*
 UserInfo 有 index token mobile nickName headImageUrl isFirst setting 7个字段
 index 默认为0 Int 作为条件查询
 isFirst
 token 口令 String
 mobile 手机号 String
 nickName 昵称 String
 headImageUrl 头像 String
 setting 用户设置（认证信息）String 实际上是NSDictionary转换的jsonString
 */

enum InsuranceInfoType {
    case rbCode
    case quotationType
    case kinds
    case vclStartDate
    case tclStartDate
    case cityCode
    case id
    case newType
    case providerCode
    case providerName
    case model
    case cityName
    case townName
    case provinceName
    case underwriteItem
    case unKnow
}


/*
 InsuranceInfo 有好多地段 不列举了
 index 默认为0 Int 作为条件查询
 rbCode            车辆唯一标识号
 quotationType     保险类型 1单交强 2单商业 3交商同保
 kinds             险种字典 Dictionary 转换 JsonString
 vclStartDate      商业险起期
 tclStartDate      交强险起期
 cityCode          城市代码
 id                车险流程ID
 newType           车险流程类型 1有历史数据 0没有历史数据
 providerCode      保险公司代码
 providerName      保险公司名称
 model             车险类型 online线上 offine线下
 cityName          所选市名称
 townName          所选区名称
 provinceName      所选省名称
 underwriteItem    核保所需要的图片
 */

let QueryCondition = "index = '0'"

let USERINFO = "UserInfo"             //用户信息实体
let INSURANCEINFO = "InsuranceInfo"   //车险信息实体

func getContext() -> NSManagedObjectContext {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    return appDelegate.persistentContainer.viewContext
}

//MARK:- 获取UserInfo实体的全部数据
func getUserInfo() {
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:USERINFO)
    do {
        let searchResults = try getContext().fetch(fetchRequest)
        print("number of '\(searchResults.count)'")
        
        for u in (searchResults as! [NSManagedObject]) {
            print("index : '\(u.value(forKey: "index"))'")
            print("token : '\(u.value(forKey: "token"))'")
            print("mobile : '\(u.value(forKey: "mobile"))'")
            print("nickName : '\(u.value(forKey: "nickName"))'")
            print("headImageUrl : '\(u.value(forKey: "headImageUrl"))'")
            print("setting : '\(u.value(forKey: "setting"))'")
        }
    } catch {
        print(error)
    }
}

//MARK:- 更新UserInfo的某个字段
func saveUserInfo(key:String,_ value :String) {
    let context = getContext()
    let requset: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName:USERINFO)
    let entity:NSEntityDescription = NSEntityDescription.entity(forEntityName: USERINFO, in: context)!
    let predicate = NSPredicate(format:QueryCondition,"")
    requset.entity = entity
    requset.predicate = predicate
    
    do {
        let userlist = try context.fetch(requset)
        if userlist.isEmpty {
            //新建一条
            let user = NSManagedObject(entity:entity,insertInto:context)
            user.setValue(0, forKey: "index")
            user.setValue(value, forKey: key)
            
            do {
                try context.save()
            } catch {
                print(error)
            }
            
        } else {
            for u in (userlist as! [NSManagedObject]) {
                u.setValue(value, forKey: key)
                try context.save()
            }
        }
    } catch {
        print(error)
    }
}

//MARK:- 查询UserInfo某个字段对应的值
func getUserInfo(_ key:UserInfoType) -> String {
    let context = getContext()
    let request:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName:USERINFO)
    let entity:NSEntityDescription = NSEntityDescription.entity(forEntityName: USERINFO, in: context)!
    let predicate = NSPredicate(format:QueryCondition,"")
    request.entity = entity
    request.predicate = predicate
    
    do {
        let userlist = try context.fetch(request)
        if userlist.isEmpty {
            return String()
        } else {
            for item in userlist {
                let u = item as! UserInfo
                switch key {
                case .token:
                    return u.token!
                case .mobile:
                    return u.mobile!
                case .isFirst:
                    return u.isFirst!
                case .headImageUrl:
                    return u.headImageUrl!
                case .nickName:
                    return u.nickName!
                case .setting:
                    return u.setting!
                default:
                    return String()
                }
            }
        }
    } catch {
        print(error)
    }
    
    return String()
}

//MARK:- 更新USerInfo表,登出的时候清空信息
func clearUserInfo() {
    let context = getContext()
    let request:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName:USERINFO)
    let entity:NSEntityDescription = NSEntityDescription.entity(forEntityName: USERINFO, in: context)!
    let predicate = NSPredicate(format:QueryCondition,"")
    request.entity = entity
    request.predicate = predicate
    do {
        let userlist = try context.fetch(request)
        if userlist.isEmpty {
            
        } else {
            for item in userlist {
                let u = item as! UserInfo
                u.token = ""
                u.setting = ""
            }
            
            try context.save()
        }
    } catch {
        print(error)
    }
}

//MARK:- 获取InsuranceInfo的所有信息
func getInsuranceInfo()
{
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:INSURANCEINFO)
    do {
        let searchResults = try getContext().fetch(fetchRequest)
        print("number of '\(searchResults.count)'")
        
        for u in (searchResults as! [NSManagedObject]) {
            print("index : '\(u.value(forKey: "index"))'")
            print("rbCode : '\(u.value(forKey: "rbCode"))'")
            print("quotationType : '\(u.value(forKey: "quotationType"))'")
            print("kinds : '\(u.value(forKey: "kinds"))'")
            print("vclStartDate : '\(u.value(forKey: "vclStartDate"))'")
            print("tclStartDate : '\(u.value(forKey: "tclStartDate"))'")
            print("cityCode : '\(u.value(forKey: "cityCode"))'")
            print("id : '\(u.value(forKey: "id"))'")
            print("newType : '\(u.value(forKey: "newType"))'")
            print("providerCode : '\(u.value(forKey: "providerCode"))'")
            print("providerName : '\(u.value(forKey: "providerName"))'")
            print("model : '\(u.value(forKey: "model"))'")
            print("cityName : '\(u.value(forKey: "cityName"))'")
            print("townName : '\(u.value(forKey: "townName"))'")
            print("provinceName : '\(u.value(forKey: "provinceName"))'")
            print("underwriteItem : '\(u.value(forKey: "underwriteItem"))'")
        }
    }
    catch {
        print(error)
    }
}

//MARK:- 更新InsuranceInfo某个字段信息
func saveInsuranceInfo(key:String,_ value :String) {
    let context = getContext()
    let requset: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName:INSURANCEINFO)
    let entity:NSEntityDescription = NSEntityDescription.entity(forEntityName: INSURANCEINFO, in: context)!
    let predicate = NSPredicate(format:QueryCondition,"")
    requset.entity = entity
    requset.predicate = predicate
    
    do {
        let userlist = try context.fetch(requset)
        if userlist.isEmpty {
            //新建一条
            let user = NSManagedObject(entity:entity,insertInto:context)
            user.setValue(0, forKey: "index")
            user.setValue(value, forKey: key)
            
            do {
                try context.save()
            } catch {
                print(error)
            }
        } else {
            for u in (userlist as! [NSManagedObject]) {
                u.setValue(value, forKey: key)
                try context.save()
            }
        }
    } catch {
        print(error)
    }
}

//MARK:- 查询InsuranceInfo某个字段信息对应的值
func getInsuranceInfo(_ key:InsuranceInfoType) -> String {
    let context = getContext()
    let request:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName:INSURANCEINFO)
    let entity:NSEntityDescription = NSEntityDescription.entity(forEntityName: INSURANCEINFO, in: context)!
    let predicate = NSPredicate(format:QueryCondition,"")
    request.entity = entity
    request.predicate = predicate
    
    do {
        let userlist = try context.fetch(request)
        if userlist.isEmpty {
            return String()
        } else {
            for item in userlist {
                let i = item as! InsuranceInfo
                
                switch key {
                case .rbCode:
                    return i.rbCode!
                case .quotationType:
                    return i.quotationType!
                case .kinds:
                    return i.kinds!
                case .vclStartDate:
                    return i.vclStartDate!
                case .tclStartDate:
                    return i.tclStartDate!
                case .cityCode:
                    return i.cityCode!
                case .id:
                    return i.id!
                case .newType:
                    return i.newType!
                case .providerCode:
                    return i.providerCode!
                case .providerName:
                    return i.providerName!
                case .model:
                    return i.model!
                case .cityName:
                    return i.cityName!
                case .townName:
                    return i.townName!
                case .provinceName:
                    return i.provinceName!
                case .underwriteItem:
                    return i.underwriteItem!
                default:
                    return String()
                }
                
                
            }
        }
    } catch {
        print(error)
    }
    return String()
}

//MARK:- 清空InsuranceInfo所有信息 这里不需要清空信息 直接覆盖就行
func clearInsuranceInfo() {
    
}
